<template>
  <view class="charging-container">
    <view class="station-info">
      <view class="station-name">{{ gunDetail.plotName }} </view>
      <view class="device-id">设备: {{ gunDetail.deviceName }}</view>
      <view class="device-id">枪号: {{ gunDetail.portCode }}</view>
      <view class="price">
        <text class="number">{{ gunDetail.price }}</text>
        <text class="unit">元/度</text>
        <text class="view-standard" @click="viewPriceStandard">查看收费标准 ></text>
      </view>
    </view>

    <!-- Prepaid Amount Options -->
    <view class="amount-section">
      <view class="section-title">续充金额</view>
      <view class="amount-options">
        <view
          v-for="amount in prepaidAmounts"
          :key="amount"
          class="amount-option"
          :class="{ active: selectedAmount === amount && !isCustomAmount }"
          @click="selectAmount(amount)"
        >
          <text class="amount">{{ amount }}元</text>
        </view>
        <view class="amount-option custom" :class="{ active: isCustomAmount }">
          <input
            type="number"
            v-model="customAmount"
            class="custom-input"
            placeholder="其他金额"
            @focus="activateCustomAmount"
            @blur="validateCustomAmount"
          />
        </view>
      </view>
      <view class="prepaid-tips">
        <view class="tip-item">
          <text class="dot">•</text>
          <text>预付单充电完成后，未使用金额将原路退回</text>
        </view>
        <view class="tip-item">
          <text class="dot">•</text>
          <text>余额支付单充电完成后，未使用金额将充值至余额</text>
        </view>
        <view class="tip-item">
          <text class="dot">•</text>
          <text>退款将在1-3个工作日内完成</text>
        </view>
      </view>
    </view>

    <!-- Start Charging Button -->
    <view class="button-section">
      <button
        class="start-charging"
        :class="{ disabled: !canStartCharging }"
        @click="handleStartCharging"
      >开始续充</button>
      <text class="tip">小提示：充电过程中请勿自拔充电口</text>
    </view>

    <!-- Price Standard Popup -->
    <u-popup v-model="showPricePopup" mode="bottom" border-radius="24">
      <view class="price-popup">
        <view class="popup-header">
          <text class="title">收费标准</text>
          <u-icon name="close" size="32" @click="showPricePopup = false"></u-icon>
        </view>
        <view class="price-list">
          <view class="price-period" v-for="(period, index) in pricePeriods" :key="index">
            <view class="period-header">
              <text class="time">{{ period.timeRange }}</text>
              <text class="type">{{ period.type }}</text>
            </view>
            <view class="period-price">
              <text class="total">{{ period.total }}元/度</text>
              <text class="breakdown">(电费{{ period.electricity }}元 + 服务费{{ period.service }}元)</text>
            </view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      paymentType: 'prepaid', // 'prepaid' or 'balance'
      selectedAmount: null,
      prepaidAmounts: [],
      showPricePopup: false,
      pricePeriods: [

      ],
      isCustomAmount: false,
      customAmount: '',
      minPaymentAmount: 0, // 最小支付金额
      maxPaymentAmount: 0, // 最大支付金额
      gunDetail: {},
      orderId: '',
      orderType: ''
    }
  },
  computed: {
    ...mapGetters(['balance']),
    canStartCharging() {
      if (this.paymentType === 'prepaid') {
        // 预付费模式：需要选择或输入有效金额
        return this.selectedAmount > 0;
      } else {
        // 余额支付模式：余额需要大于最小支付金额
        return this.balance >= this.minPaymentAmount;
      }
    }
  },
  onLoad({ portId, stationId, id, orderType  }) {
    if (orderType === 'top_up') {
      this.paymentType = 'prepaid'
    } else {
      this.paymentType = 'balance'
    }
    this.orderId = id
    this.orderType = orderType
    uni.showLoading()
    this.$api.getGunDetail({
      portId
    }).then(res => {
      this.gunDetail = res
    }).finally(() => {
      uni.hideLoading()
    })

    this.$api.getStationPriceList({
      plotId: stationId
    }).then(res => {
      this.pricePeriods = res.map(item => {
        let typeMap = {
          // 0123 尖峰平谷
          0: '尖',
          1: '峰',
          2: '平',
          3: '谷'
        }
        return {
          timeRange: `${item.startTime}-${item.endTime}`,
          type: typeMap[item.ruleType] || item.ruleType,
          total: (item.serviceMoney || 0 + item.chargingPrice || 0).toFixed(3),
          electricity: item.chargingPrice || '',
          service: item.serviceMoney || '',
        }
      })
    })
    this.getConfig()
  },
  onShow() {
    this.$store.dispatch('getBalance')
  },
  methods: {
    async getConfig() {
      uni.showLoading()
      try {
        const res1 = await this.$api.getConfig({
          code: 'prepaid_amounts'
        })
        const res2 = await this.$api.getConfig({
          code: 'min_payment_amount'
        })
        const res3 = await this.$api.getConfig({
          code: 'max_payment_amount'
        })
        this.prepaidAmounts = (res1 || '').split(',').map(item => Number(item))
        this.minPaymentAmount = res2 || 0
        this.maxPaymentAmount = res3 || 0
      } catch (e) {
        uni.hideLoading()
        console.error(e)
      }
    },
    viewPriceStandard() {
      // 查看收费标准
      this.showPricePopup = true;
    },
    goToRecharge() {
      uni.navigateTo({
        url: '/pages/wallet/recharge'
      })
    },
    handleStartCharging() {
      if (this.paymentType === 'prepaid') {
        uni.showModal({
          title: '预付单续充确认',
          content: `您选择${this.isCustomAmount ? this.customAmount : this.selectedAmount}元进行续充，充电完成后未使用金额将原路退回`,
          confirmText: '确认续充',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              this.startCharging();
            }
          }
        });
      } else {
        uni.showModal({
          title: '余额支付订单续充确认',
          content: `您选择${this.isCustomAmount ? this.customAmount : this.selectedAmount}元进行续充，充电完成后未使用金额将充值至余额`,
          confirmText: '确认续充',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              this.startCharging();
            }
          }
        });

      }
    },
    startCharging() {
      // 预支付，创建订单后，唤醒支付，支付成功后，跳转订单详情
      uni.showLoading({
        title: '发起支付...'
      })
      // 余额充电，创建成功后跳转订单详情页面
      this.$api.addPay({
        orderId: this.orderId,
        addAmount: this.isCustomAmount ? this.customAmount : this.selectedAmount
      }).then(res => {
        this.handlePay(res)
      }).finally(() => {
        uni.hideLoading()
      })
    },
    handlePay({ response, chargingOrderDO }) {
      uni.showLoading({
        title: '支付中...'
      })
      let {
        nonceStr,
        packageVal,
        signType,
        paySign,
        timeStamp,
      } = response
      let that = this
      console.log(response,'response')
      uni.requestPayment({
        timeStamp,
        nonceStr,
        package: packageVal,
        signType,
        paySign,
        success: (res) => {
          console.log('支付成功', res)
          uni.showToast({
            title: '支付成功',
            icon: 'success'
          })
          setTimeout(() => {
            that.toOrderDetail()
          },1000)
        },
        fail: (err) => {
          console.error('支付失败', err)
          uni.showToast({
            title: '支付失败',
            icon: 'none'
          })
        },
      })
    },
    toOrderDetail() {
      uni.redirectTo({
        url: '/pages/order/charging?id=' + this.orderId
      })
    },
    selectAmount(amount) {
      this.selectedAmount = amount
      this.isCustomAmount = false
      this.customAmount = '' // 清除自定义金额
    },
    activateCustomAmount() {
      this.isCustomAmount = true
      this.selectedAmount = 0 // 清除选中金额
    },
    validateCustomAmount() {
      const amount = parseFloat(this.customAmount)
      if (this.customAmount === '') {
        this.isCustomAmount = false
        this.selectedAmount = 0 // 清除选中金额
        return
      }

      if (isNaN(amount) || amount <= 0) {
        uni.showToast({
          title: '请输入有效金额',
          icon: 'none'
        })
        this.customAmount = ''
        this.isCustomAmount = false
        this.selectedAmount = 0 // 清除选中金额
        return
      }

      if (amount > 9999) {
        uni.showToast({
          title: '金额不能超过9999元',
          icon: 'none'
        })
        this.customAmount = ''
        this.isCustomAmount = false
        this.selectedAmount = 0 // 清除选中金额
        return
      }

      this.selectedAmount = amount
      this.isCustomAmount = true
    }
  }
}
</script>

<style lang="scss" scoped>
.price-popup {
  padding: 32rpx;
  max-height: 80vh;
  overflow-y: auto;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32rpx;

    .title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
    }
  }

  .price-list {
    .price-period {
      margin-bottom: 24rpx;
      padding: 24rpx;
      background: #F8F9FC;
      border-radius: 12rpx;

      .period-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12rpx;

        .time {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
        }

        .type {
          font-size: 24rpx;
          color: #04C8AE;
          background: rgba(4, 200, 174, 0.1);
          padding: 4rpx 12rpx;
          border-radius: 4rpx;
        }
      }

      .period-price {
        .total {
          font-size: 32rpx;
          color: #333;
          font-weight: 500;
        }

        .breakdown {
          font-size: 24rpx;
          color: #666;
          margin-left: 12rpx;
        }
      }
    }

    .price-notes {
      margin-top: 32rpx;
      padding: 24rpx;
      background: #FFF7F2;
      border-radius: 12rpx;

      .note-item {
        display: flex;
        align-items: center;
        margin-bottom: 12rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .dot {
          color: #FF6B01;
          margin-right: 8rpx;
        }

        text {
          font-size: 24rpx;
          color: #666;
        }
      }
    }
  }
}
.charging-container {
  min-height: 100vh;
  background: #F5F5F5;
  padding: 24rpx;

}

.station-info {
  background: #FFFFFF;
  padding: 24rpx;
  border-radius: 16rpx;

  .station-name {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
  }

  .device-id {
    font-size: 28rpx;
    color: #666;
    margin: 8rpx 0;
  }

  .price-info {
    font-size: 28rpx;
    color: #666;
  }

  .price {
    display: flex;
    align-items: baseline;
    margin-top: 16rpx;

    .number {
      font-size: 48rpx;
      font-weight: 500;
      color: #333;
    }

    .unit {
      font-size: 28rpx;
      color: #666;
      margin-left: 8rpx;
    }

    .view-standard {
      font-size: 24rpx;
      color: #04C8AE;
      margin-left: auto;
    }
  }
}

.payment-section, .amount-section {
  background: #FFFFFF;
  padding: 24rpx;
  border-radius: 16rpx;
  margin-top: 24rpx;

  .section-title {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 16rpx;
  }
}

.payment-types {
  display: flex;
  gap: 24rpx;

  .payment-type {
    flex: 1;
    padding: 24rpx;
    border-radius: 12rpx;
    background: #F8F9FC;
    text-align: center;

    text {
      display: block;
      font-size: 28rpx;
      color: #333;
    }

    .desc {
      font-size: 24rpx;
      color: #666;
      margin-top: 8rpx;
    }

    &.active {
      background: rgba(4, 200, 174, 0.1);
      border: 2rpx solid #04C8AE;

      text {
        color: #04C8AE;
      }
    }
  }
}

.amount-options {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;

  .amount-option {
    width: calc(33.33% - 16rpx);
    height: 88rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #F8F9FC;
    border-radius: 12rpx;
    font-size: 28rpx;
    color: #333;

    &.active {
      background: rgba(4, 200, 174, 0.1);
      border: 2rpx solid #04C8AE;
      color: #04C8AE;
    }

    &.custom {
      padding: 0;

      .custom-input {
        width: 100%;
        height: 88rpx;
        padding: 0 24rpx;
        font-size: 28rpx;
        color: #333;
        background: #fff;
        border: 2rpx solid #EBEDF0;
        border-radius: 12rpx;
        text-align: center;

        &::placeholder {
          color: #999;
        }
      }

      &.active .custom-input {
        border-color: #04C8AE;
        background: rgba(4, 200, 174, 0.05);
      }
    }
  }
}

.balance-info {
  display: flex;
  align-items: center;
  padding: 24rpx;
  background: #F8F9FC;
  border-radius: 12rpx;

  text {
    font-size: 28rpx;
    color: #666;
  }

  .balance {
    font-size: 32rpx;
    color: #333;
    font-weight: 500;
    margin-left: 16rpx;
  }

  .recharge-btn {
    margin-left: auto;
    padding: 12rpx 24rpx;
    background: #04C8AE;
    border-radius: 24rpx;
    color: #FFFFFF;
    font-size: 24rpx;
  }
}

.amount-section {
  padding: 32rpx;
  background: #FFFFFF;
  border-radius: 24rpx;
  margin: 24rpx 0;

  .section-title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 24rpx;
  }

  .prepaid-tips {
    margin-top: 24rpx;
    padding: 24rpx;
    background: #F8F9FC;
    border-radius: 12rpx;

    .tip-item {
      display: flex;
      align-items: center;
      margin-bottom: 12rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .dot {
        color: #04C8AE;
        margin-right: 8rpx;
      }

      text {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.button-section {
  padding: 32rpx;

  .start-charging {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    background: #04C8AE;
    color: #fff;
    font-size: 32rpx;
    border-radius: 44rpx;
    border: none;
    margin-bottom: 24rpx;

    &.disabled {
      background: #CCCCCC;
      opacity: 0.6;
      cursor: not-allowed;
    }
  }

  .tip {
    display: block;
    text-align: center;
    font-size: 24rpx;
    color: #999;
  }
}
</style>
